package com.ray.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.ray.bean.ApplyRepairFormBean;
import com.ray.bean.CompanyBean;
import com.ray.bean.CompanyMaterialCountBean;
//import com.google.appengine.api.search.query.ExpressionParser.negation_return;
import com.ray.bean.CompanyMaterialTableBean;
import com.ray.bean.CompanyMaterialTypeBean;
import com.ray.bean.CustomerBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.FeedUseMaterialCountBean;
import com.ray.bean.MaterialPositionBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.bean.OtherWarehouseBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.PurchaseDetailBean;
import com.ray.bean.PurchaseOrderDetailBean;
import com.ray.bean.ReceiptPaymentRecordBean;
import com.ray.bean.ReportBean;
import com.ray.bean.UserBean;
import com.ray.bean.WarehouseInOutDetailBean;
import com.ray.bean.WarehouseInSumMoneyBean;
import com.ray.bean.WorkshopProductionCycleBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.AdvancePurchaseMapepr;
import com.ray.mapper.ApplyRepairFormMapper;
import com.ray.mapper.BasicDataMapper;
import com.ray.mapper.CompanyMapper;
import com.ray.mapper.CompanyMaterialMapper;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.FeedUseMaterialCountMapper;
import com.ray.mapper.MaterialPositionMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.OtherWarehouseMapper;
import com.ray.mapper.ProductionUnitFeedMapper;
import com.ray.mapper.UserMapper;
import com.ray.mapper.WarehouseInSumMoneyMapper;
import com.ray.mapper.WorkshopMapper;
import com.ray.pojo.MyUser;
import com.ray.util.CreateIdUtil;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONArray;

@Service
public class CompanyMaterialService {
	
	@Autowired
	CompanyMaterialMapper companyMaterialMapper;
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	OrderService orderService;
	@Autowired
	BasicDataService basicDataService;
	@Autowired
	BasicDataMapper basicDataMapper;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	WarehouseInSumMoneyMapper warehouseInSumMoneyMapper;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	WeiXinPeopleService weiXinPeopleService;
	@Autowired
	UserService userService;
	@Autowired
	ApprovalService approvalService;
	@Autowired
	WorkshopMapper workshopMapper;
	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	OtherWarehouseMapper otherWarehouseMapper;
	@Autowired
	DingTalkMapper DingTalkMapper;
	@Autowired
	ApplyRepairFormMapper applyRepairFormMapper;
	@Autowired
	StructureTreeService structureTreeService;
	@Autowired
	ProductionUnitFeedMapper productionUnitFeedMapper;
	@Autowired
	WeChatToMessageService weChatToMessageService;
	@Autowired
	FeedUseMaterialCountMapper feedUseMaterialCountMapper;
	@Autowired
	AdvancePurchaseMapepr advancePurchaseMapper;
	@Autowired
	CompanyMaterialTypeService companyMaterialTypeService;
	@Autowired
	UserMapper userMapper;
	@Autowired
	DingTalkMapper dingTalkMapper;
	@Autowired
	MaterialPositionMapper materialPositionMapper;
	@Autowired
	CompanyMaterialCountService companyMaterialCountService;
	@Autowired
	WarehouseInSumMoneyService warehouseInSumMoneyService;
	
	//获取所有供应商
	public List<String> getProviderName(Map map) {
		return companyMaterialMapper.getProviderName(map);
	}
	
	//查询公司供应商和商城的公司
	public List<Map> getProviderNameAndShoppingCallCompany(Map map) {
		return companyMaterialMapper.getProviderNameAndShoppingCallCompany(map);
	}
	

	//获取采购人
	public List<UserBean> getPurchasePeople(Map map) {
		return companyMaterialMapper.getPurchasePeople(map);
	}

	//获取采购订单编号
	public List<String> getPurchaseId(Map map) {
		return companyMaterialMapper.getPurchaseId(map);
	}

	//插入入库记录
	public void  insertInOutRecode(List<WarehouseInOutDetailBean> inOutList) {
		companyMaterialMapper.insertInOutRecode(inOutList);
	}

	//根据供应商查询物料信息
	public List<String> getMaterialTypeByProviderName(Map map) {
		return companyMaterialMapper.getMaterialTypeByProviderName(map);
	}

	//获取物料信息
	public DatatablesViewPageBean<CompanyMaterialTableBean> getMaterialDate(Map map) {
		Object idsOjb = map.get("ids");
		if(idsOjb!=null) {
			String [] ids = idsOjb.toString().split(",");
			map.put("ids",ids);
		}
		int count=0;
		DatatablesViewPageBean<CompanyMaterialTableBean> dtcpb=new DatatablesViewPageBean<CompanyMaterialTableBean>();
		count=companyMaterialMapper.getMaterialDateCount(map);
		dtcpb.setReturnData(companyMaterialMapper.getMaterialDate(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	public List<CompanyMaterialTableBean> getCheckMaterialTable(Map map) {
		String jsonStr=map.get("idArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(jsonStr);
		List<String> idList=jsonArray.subList(0, jsonArray.size());
		map.put("idList", idList);
		return companyMaterialMapper.getCheckMaterialTable(map);
	}

	//获取出入库数据
	public DatatablesViewPageBean getInWarehourseNotApprovalData(Map map) {
		int count=0;
		DatatablesViewPageBean<WarehouseInOutDetailBean> dtcpb=new DatatablesViewPageBean<WarehouseInOutDetailBean>();
		dtcpb.setReturnData(companyMaterialMapper.getInWarehourseNotApproval(map));
		count=companyMaterialMapper.getInWarehourseNotApprovalDataCount(map);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}
	
	
	//审核出入库单 
	public String agreeInWarehourse(Map<String, Object> map,int status,HttpServletRequest request) throws ServiceException, CloneNotSupportedException, ParseException {
		//判断审核权限
		WarehouseInOutDetailBean wiodb=companyMaterialMapper.getInWarehourseByIdOne(map.get("id").toString());
		if(wiodb.getStatus()!=0) { 
			throw new ServiceException("该出入库单已经审核了,请勿重复操作!");
		}  
		Object isApprovals = map.get("isApproval");
		if(isApprovals==null || !"1".equals(isApprovals.toString())) {
			Map<String, Object> approvalParam = new HashMap<String,Object>();
			approvalParam.put("type","6"); 
			approvalParam.put("loginUserId", map.get("loginUserId"));
			approvalParam.put("loginCompany", map.get("loginCompany"));
			List<String> userIds = approvalService.getApprovalIdByLoginId(approvalParam);
			int isApproval = 0;
			if(userIds !=null && userIds.size()>0) {
				for(String createUserId:userIds) {
					if(createUserId.equals(wiodb.getCreateUser())) {
						isApproval = 1;
						break;
					}
				}
			}
			if(isApproval==0) { 
				throw new ServiceException("您暂无权限审核此出入库单!");
			}
		}
		//判断是否重复操作
		SimpleDateFormat sdf =new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
		map.put("approvalTime", sdf.format(new Date()));
		map.put("approvalUser", map.get("loginUserId"));
		Map<String,Object> materialParam = new HashMap<String,Object>(); 
		map.remove("materialCode");
		map.put("materialCode", wiodb.getMaterialCode());
		//获取物料信息
		CompanyMaterialTableBean cmtb = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(map);
		String feedDetailId = null;
		//审核通过
		String tishi=""; 
		if(status==1) {
			tishi="确认"; 
			List<CompanyMaterialTableBean> listCmtb=new ArrayList<CompanyMaterialTableBean>();
			if(cmtb.getColor()==null) {
				cmtb.setColor("");
			}
			Assert.isTrue(cmtb!=null,"物料不存在");
			//物料单位库存数量
			BigDecimal materialCount = new BigDecimal(cmtb.getCount().toString());
			//生产单位库存数量
			BigDecimal productionUniCount = new BigDecimal(cmtb.getProductionUnitCount().toString());
			//出入库数量
			BigDecimal count = new BigDecimal(wiodb.getCount().toString());
			if(wiodb.getType()==2 || wiodb.getType()==5  || wiodb.getType()==9) {//是出库
				if(wiodb.getCount()==null ||wiodb.getCount().doubleValue()<=0) {
					throw new ServiceException("出库数量异常");
				}
				//出库单位与物料单位一致
				if(wiodb.getInOutUnit().equals(cmtb.getUnit())) {
					if(materialCount.subtract(count).doubleValue()<0) {
						throw new ServiceException("库存不足");
					}
					cmtb.setCount(materialCount.subtract(count).doubleValue()); 
				}else {
					if(productionUniCount.subtract(count).doubleValue()<0) {
						throw new ServiceException("库存不足");
					}
					cmtb.setProductionUnitCount(productionUniCount.subtract(count).doubleValue()); 
				}
				
				if(wiodb.getType()==2) {//投料单出库
					feedDetailId = wiodb.getFeedOrder();
					if(feedDetailId==null || feedDetailId.trim().equals("")) {
						throw new ServiceException("投料单明细id为空异常");
					}
					FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(feedDetailId);
					if(feedOrderDetailBean==null) {
						throw new ServiceException("投料单明细常");
					}
					Double feedCount = feedOrderDetailBean.getFeedCount();
					Double productionFeedCount = feedOrderDetailBean.getProductionUnitFeedCount();
					Map<String,Object> feedUseCountMap = new HashMap<String,Object>();
					feedUseCountMap.put("feedDetailId", feedOrderDetailBean.getId());
					feedUseCountMap.put("loginCompany", map.get("loginCompany"));
					//查询当前投料单是否有占用
					List<FeedUseMaterialCountBean> feedUseMaterialCountBeans = feedUseMaterialCountMapper.getFeedUseMaterialCountByFeedDetailId(feedUseCountMap);
					if(feedUseMaterialCountBeans!=null && feedUseMaterialCountBeans.size()>0) {
						//当前投料单出库信息(原料仓的)
						//物料单位与出库单位一致的
						if(wiodb.getInOutUnit().equals(cmtb.getUnit())) {
							if(feedCount.doubleValue()<=0) {
								throw new ServiceException("投料数小于0异常");
							}
							List<WarehouseInOutDetailBean> warehouseInOutDetailBeans =  orderMapper.getWarehouseInOutDetailByFeedDetailId(feedUseCountMap);
							BigDecimal materialOutCount = new BigDecimal("0.0");
							if(warehouseInOutDetailBeans!=null && warehouseInOutDetailBeans.size()>0) {
								for(WarehouseInOutDetailBean warehouseInOutDetailBean:warehouseInOutDetailBeans) {
									if(warehouseInOutDetailBean.getCount()==null) {
										throw new ServiceException("关联出库数量为空异常");
									} 
									materialOutCount = materialOutCount.add(new BigDecimal(warehouseInOutDetailBean.getCount().toString()));
								}
							} 
							BigDecimal otherOutCount = new BigDecimal("0.0");
							//采购单投料单对应表id
							String purchaseDetailId = orderMapper.getPurchaseDetailIdByFeedDetailId(feedUseCountMap);
							feedUseCountMap.put("purchaseDetailId", purchaseDetailId);
							//其他仓位的出库数量
							otherOutCount = new BigDecimal(otherWarehouseMapper.getOtherWarehouseByPurchaseId(feedUseCountMap)+"");
							//投料单占用数
							FeedUseMaterialCountBean feedUseMaterialCountBean = feedUseMaterialCountBeans.get(0);
							Double feedUseCount = feedUseMaterialCountBean.getFeedUseCount();
							//投料数-其他仓库出库数-原料仓出库数-当前要出库的数量小于占用数
							if(new BigDecimal(feedCount.toString()).subtract(materialOutCount).subtract(otherOutCount).subtract(new BigDecimal(wiodb.getCount().toString())).subtract(new BigDecimal(feedUseCount.toString())).doubleValue()<0) {
								feedUseMaterialCountBean.setFeedUseCount(new BigDecimal(feedCount.toString()).subtract(materialOutCount).subtract(otherOutCount).subtract(BigDecimal.valueOf(wiodb.getCount().doubleValue())).doubleValue());
								int feedUseRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBean);
								if(feedUseRow<1) {
									throw new ServiceException("更新投料单占用数异常");
								}
							}
						}else {
							FeedUseMaterialCountBean feedUseMaterialCountBean = feedUseMaterialCountBeans.get(0);
							if(productionFeedCount.doubleValue()<=0) {
								throw new ServiceException("投料数小于0异常");
							}
							BigDecimal bigProductionUnitCount = new BigDecimal(feedUseMaterialCountBean.getProductionUnitUseCount().toString());
							feedUseMaterialCountBean.setProductionUnitUseCount(bigProductionUnitCount.subtract(count).doubleValue());
							int feedUseRow = feedUseMaterialCountMapper.updateFeedUseCount(feedUseMaterialCountBean);
							if(feedUseRow<1) {
								throw new ServiceException("更新投料单占用数异常");
							}
						}
					} 
				} 
				materialParam.put("type","出库"); 
			}else {//入库 
				if(wiodb.getType()==7) {
					//入库数量 
					BigDecimal inCount = new BigDecimal(wiodb.getCount().toString());
					//如果入库单位和生产单位相同
					if(cmtb.getUnit().equals(wiodb.getInOutUnit())) {
						//物料单位库存数
						BigDecimal cmtbCount = new BigDecimal(cmtb.getCount().toString());
						cmtb.setCount(cmtbCount.add(inCount).doubleValue());
					}else {
						//生产单位库存数
						BigDecimal cmtbCount = new BigDecimal(cmtb.getProductionUnitCount().toString());
						cmtb.setProductionUnitCount(cmtbCount.add(inCount).doubleValue());
					}
					materialParam.put("type","入库");
				}else { 
					cmtb.setCount(materialCount.add(count).doubleValue());
					materialParam.put("type","入库");
				}
			} 
			listCmtb.add(cmtb);
			wiodb.setStatus(1);
			map.put("listCompanyMaterial", listCmtb);
			companyMaterialMapper.updateCompanyMaterialTable(map);
			
			/**
			 * 采购单入库时,判断供应商是否为现金结算,如果是,那么就自动结算了
			 */
			if((wiodb.getType()==1 || wiodb.getType()==3) && status == 1) {
				autoSumMoneyByWarehouseIn(wiodb, map);
			}
		}else{//退回出入库
			if(wiodb.getType()==2) { 
				List<FeedOrderDetailBean> feedList=new ArrayList<FeedOrderDetailBean>();
				FeedOrderDetailBean feedDeatil=orderService.getFeedOrderDetailOneById(wiodb.getFeedOrder());
				if(cmtb.getUnit().equals(wiodb.getInOutUnit())) {
					BigDecimal receiveCount = new BigDecimal(feedDeatil.getReceiveCount().toString());
					BigDecimal count = new BigDecimal(wiodb.getCount().toString());
					feedDeatil.setReceiveCount(receiveCount.subtract(count).doubleValue());
					feedDeatil.setIsReceiveFinish(0);
				}else {
					BigDecimal receiveCount = new BigDecimal(feedDeatil.getProductionUnitReceiveCount().toString());
					BigDecimal count = new BigDecimal(wiodb.getCount().toString());
					feedDeatil.setProductionUnitReceiveCount(receiveCount.subtract(count).doubleValue());
					feedDeatil.setIsReceiveFinish(0); 
				}
				Map paramMap=new HashMap();
				feedList.add(feedDeatil);
			    //修改投料单明细的领料数
			    paramMap.put("feedList", feedList);
			    companyMaterialMapper.updateFeedOrderDetailReceive(paramMap);
			}
			//订单采购入库退回
			if(wiodb.getType()==1) {
				List<PurchaseOrderDetailBean> list=new ArrayList<PurchaseOrderDetailBean>();
				PurchaseOrderDetailBean podb=companyMaterialMapper.getPurchaseOrderDetailById(wiodb.getPurcharseOrderId());
				BigDecimal podbInCount = new BigDecimal(podb.getInCount().toString());
				BigDecimal count = new BigDecimal(wiodb.getCount().toString());
				podb.setInCount(podbInCount.subtract(count).doubleValue());
				podb.setIsFinish(0);
				list.add(podb);
				companyMaterialMapper.updatePurchaseOrderDetail(list);
			}
			//库存采购入库 
			if(wiodb.getType()==3) {
				PurchaseDetailBean podb=companyMaterialMapper.getPurchaseDetailById(wiodb.getPurcharseOrderId());
				BigDecimal podbInCount = new BigDecimal(podb.getInCount().toString());
				BigDecimal count = new BigDecimal(wiodb.getCount().toString());
				podb.setInCount(podbInCount.subtract(count).doubleValue());
				podb.setIsFinish(0);
			    companyMaterialMapper.updatePurchaseDetailOne(podb);
			}  
			wiodb.setApprovalReason(map.get("approvalReason").toString());
			wiodb.setStatus(2);
			tishi="退回";
			materialParam.put("type","出入库");
		}
		if(wiodb.getType()==7) {
			String id=map.get("id").toString();
			map.remove("id");
			map.put("otherId", id);
			map.put("approvalReason", "仓库"+tishi);
			map.put("time", map.get("approvalTime"));
			workshopService.approvalReportByOtherId(map);
			map.put("id", id);
			materialParam.put("type","入库");
		}
		companyMaterialMapper.updateWarehouseInOutOne(map);
		//审核通过并且是投料单领料
		Object isTryObj = map.get("isTcy");
		String isTry = ""; 
		if(isTryObj!=null) {
			isTry = isTryObj.toString();
		}
		if(status == 1 && wiodb.getType() == 2 && !isTry.equals("2")) {
			/**
			 * 投料单出库,审核通过后交接至车间
			 * 李斌
			 */ 
			map.put("feedDetailId", feedDetailId);
			FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(feedDetailId);
			if(feedOrderDetailBean==null) {
				throw new ServiceException("投料单明细为空异常");
			}
			if(feedOrderDetailBean.getType()==2) {
				ApplyRepairFormBean applyRepairFormBean = applyRepairFormMapper.getApplyByFeedDetailId(map);
				if(applyRepairFormBean==null) {
					throw new ServiceException("申补投料单明细为空异常");
				}  
				if(applyRepairFormBean.getType()==1) {
					return "损耗的申补单无需交接车间"; 
				}
			} 
			MyUser myUser = RequestUtil.getLoginUser(request);
			String reportJSONStr =  this.getReportDataByWarehouse(wiodb,myUser,sdf.format(new Date()));
			if(!isTry.equals("1")) {
				try { 
					workshopService.insertReport(reportJSONStr, wiodb.getCreateUser(), myUser);
				} catch (ServiceException e) {
					if(e.getMessage().indexOf("车间最多还可入库或领料")>0) { //如果异常中有这五个字
						//手动回滚
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return "重新确认"; 
					}else {
						throw e;
					}
				} 
			}else {
				workshopService.insertReport(reportJSONStr, wiodb.getCreateUser(), myUser);
			}
			
			
			  
			
		}
		/**
		 * 发送库存不足警报
		 * 当出库确认时
		 */
		if((wiodb.getType()==2 || wiodb.getType()==5) && status == 1) {
			if(cmtb.getCount()<cmtb.getSafetyStockMin()) {
				String dateString = sdf.format(new Date());
				String title = "库存不足报警";
				String bodyMessage = "物料名称-"+cmtb.getMaterialName()+" 物料规格-"+(cmtb.getModel()==null?"":cmtb.getModel())+" 色号-"+(cmtb.getColor()==null?"":cmtb.getColor())+" 供应商-"+cmtb.getProviderName()+" ---目前库存数:"+cmtb.getCount();
				this.sendSafetyStockMinMessage(title, bodyMessage, dateString, map, RedirectUrlUtil.queryStock,"8",0);
			}
		} 
		
		/**
		 * 发消息审核通知
		 */
		return  workshopService.sendApprovalStatusMassage(status, wiodb.getCreateUser(), map.get("loginUserName").toString(), materialParam.get("type")+"单", RedirectUrlUtil.queryWarehouse);
		
		
	}
 
	//修改
	public void updateWarehouseInOut(Map map) throws ServiceException {
		List<WarehouseInOutDetailBean> xx=new ArrayList<WarehouseInOutDetailBean>();
		Double count=Double.parseDouble(map.get("count").toString());
		//修改数
		BigDecimal bigCount = new BigDecimal(count.toString());
		WarehouseInOutDetailBean wiodb=companyMaterialMapper.getInWarehourseByIdOne(map.get("id").toString());
		if(wiodb.getStatus() != 0) { 
			throw new ServiceException("该出入库单已审核,不能修改");
		} 
		map.put("materialCode", wiodb.getMaterialCode());
		if(wiodb.getType()==1) {//订单采购入库 
			List<PurchaseOrderDetailBean> list=new ArrayList<PurchaseOrderDetailBean>();
			PurchaseOrderDetailBean podb=companyMaterialMapper.getPurchaseOrderDetailById(wiodb.getPurcharseOrderId());
			//采购数
			BigDecimal bigPurchaseCount = new BigDecimal(podb.getPurchaseCount().toString());
			//采购入库数
			BigDecimal bigInCount = new BigDecimal(podb.getInCount().toString());
			//上次入库数
			BigDecimal bigOldInCount = new BigDecimal(wiodb.getCount().toString());
			//入库允许修改数
			BigDecimal bigAllowUpdateCount = bigPurchaseCount.subtract(bigInCount).add(bigOldInCount);
			if(bigCount.subtract(bigAllowUpdateCount).doubleValue()>0) {//如果修改数大于允许修改数
				throw new ServiceException("最大修改数为"+bigAllowUpdateCount.doubleValue());
			}else if(bigCount.subtract(bigAllowUpdateCount).doubleValue()==0){
				podb.setIsFinish(1);
			}else {
				podb.setIsFinish(0);
			}
			podb.setInCount(bigOldInCount.subtract(bigOldInCount).add(bigCount).doubleValue());
			list.add(podb);
			companyMaterialMapper.updatePurchaseOrderDetail(list);
		}else if(wiodb.getType()==3) {//库存采购入库
			PurchaseDetailBean podb=companyMaterialMapper.getPurchaseDetailById(wiodb.getPurcharseOrderId());
			//采购数
			BigDecimal bigPurchaseCount = new BigDecimal(podb.getPurchaseCount().toString());
			//采购入库数
			BigDecimal bigInCount = new BigDecimal(podb.getInCount().toString());
			//上次入库数
			BigDecimal bigOldInCount = new BigDecimal(wiodb.getCount().toString());
			//入库允许修改数
			BigDecimal bigAllowUpdateCount = bigPurchaseCount.subtract(bigInCount).add(bigOldInCount);
			if(bigCount.subtract(bigAllowUpdateCount).doubleValue()>0) {//如果修改数大于允许修改数
				throw new ServiceException("最大修改数为"+bigAllowUpdateCount.doubleValue());
			}else if(bigCount.subtract(bigAllowUpdateCount).doubleValue()==0){
				podb.setIsFinish(1);
			}else {
				podb.setIsFinish(0);
			}
			podb.setInCount(bigOldInCount.subtract(bigOldInCount).add(bigCount).doubleValue());
		    companyMaterialMapper.updatePurchaseDetailOne(podb);
		}else if(wiodb.getType()==4){//无采购单入库什么都不用做
			
		}else if(wiodb.getType()==2){//如果是投料单领料
			CompanyMaterialTableBean cmtb=companyMaterialMapper.getCompanyMaterialTableByMaterialCode(map);
			if(cmtb==null) {
				throw new ServiceException("物料信息为空异常");
			}
			//通过出库数据查找投料单明细
			List<FeedOrderDetailBean> feedList=new ArrayList<FeedOrderDetailBean>();
			FeedOrderDetailBean feedDeatil=orderService.getFeedOrderDetailOneById(wiodb.getFeedOrder());
			//如果出库记录中的单位和物料单位一致,说明是物料单位出库
			if(cmtb.getUnit().equals(wiodb.getInOutUnit())) {
				//物料单位投料数
				BigDecimal bigFeedCount = new BigDecimal(feedDeatil.getFeedCount().toString());
				//物料单位投料单可领数
				BigDecimal bigReceiveCount = new BigDecimal(feedDeatil.getReceiveCount().toString());
				//物料单位上次出库数
				BigDecimal bigOldOutCount = new BigDecimal(wiodb.getCount().toString());
				//物料单位最大可领数
				BigDecimal bigAllowUpdateCount = bigFeedCount.subtract(bigReceiveCount).add(bigOldOutCount);
				//库存数量
				BigDecimal bigMaterialCount = new BigDecimal("0.0");
				if(cmtb.getCount()!=null) {
					bigMaterialCount = new BigDecimal(cmtb.getCount().toString());
				} 
				if(bigMaterialCount.subtract(bigCount).doubleValue()<0) { 
					throw new ServiceException("库存不足,剩余可修改数为:"+bigMaterialCount);
				}
				if(bigCount.subtract(bigAllowUpdateCount).doubleValue()>0) {//如果修改数大于允许修改数
					throw new ServiceException("最大修改数为"+bigAllowUpdateCount.doubleValue());
				}
				feedDeatil.setReceiveCount(bigReceiveCount.subtract(bigOldOutCount).add(bigCount).doubleValue());
			}else {//生产单位出库
				//生产单位投料数
				BigDecimal bigFeedCount = new BigDecimal(feedDeatil.getProductionUnitFeedCount().toString());
				//生产单位投料单可领数
				BigDecimal bigReceiveCount = new BigDecimal(feedDeatil.getProductionUnitReceiveCount().toString());
				//生产单位上次出库数
				BigDecimal bigOldOutCount = new BigDecimal(wiodb.getCount().toString());
				//生产单位最大可领数
				BigDecimal bigAllowUpdateCount = bigFeedCount.subtract(bigReceiveCount).add(bigOldOutCount);
				//库存数量
				BigDecimal bigMaterialCount = new BigDecimal("0.0");
				if(cmtb.getCount()!=null) {
					bigMaterialCount = new BigDecimal(cmtb.getProductionUnitCount().toString());
				} 
				if(bigMaterialCount.subtract(bigCount).doubleValue()<0) {
					throw new ServiceException("库存不足,剩余可修改数为:"+bigMaterialCount);
				}
				if(bigCount.subtract(bigAllowUpdateCount).doubleValue()>0) {//如果修改数大于允许修改数
					throw new ServiceException("最大修改数为"+bigAllowUpdateCount.doubleValue());
				} 
				feedDeatil.setProductionUnitReceiveCount(bigReceiveCount.subtract(bigOldOutCount).add(bigCount).doubleValue());
			}
			//物料单位出库数
			BigDecimal oldReceiveCount = new BigDecimal(feedDeatil.getReceiveCount().toString());
			//生产单位出库数
			BigDecimal oldProductionUnitReceiveCount = new BigDecimal(feedDeatil.getProductionUnitReceiveCount().toString());
			//物料单位投料数
			BigDecimal oldFeedCount = new BigDecimal(feedDeatil.getFeedCount().toString());
			//生产单位投料数
			BigDecimal oldProductionFeedCount = new BigDecimal(feedDeatil.getProductionUnitFeedCount().toString());
			if(oldReceiveCount.subtract(oldFeedCount).doubleValue()==0 && oldProductionUnitReceiveCount.subtract(oldProductionFeedCount).doubleValue()==0) {
				feedDeatil.setIsReceiveFinish(1);
			}else { 
				feedDeatil.setIsReceiveFinish(0);
			}
			feedList.add(feedDeatil); 
			//修改投料单明细的领料数
		    Map paramMap=new HashMap();
		    //修改投料单明细的领料数 
		    paramMap.put("feedList", feedList);
		    companyMaterialMapper.updateFeedOrderDetailReceive(paramMap);
		}else if(wiodb.getType()==5){//无投料单出库
			CompanyMaterialTableBean cmtb=companyMaterialMapper.getCompanyMaterialTableByMaterialCode(map);
			if(cmtb==null) {
				throw new ServiceException("物料信息为空异常");
			}
			//库存数量
			BigDecimal materialReceiveCount =new BigDecimal("0.0");
			//采购数
			BigDecimal purchaseCount = new BigDecimal("0.0");
			//排除订单的库存数
			BigDecimal notOrderMaterialCount = new BigDecimal("0.0");
			//所有投料数
			BigDecimal allFeedCount = new BigDecimal("0.0");
			Map<String, Double> mapCount =  otherWarehouseMapper.getCountResult(wiodb.getMaterialCode(),map.get("loginCompany").toString());
			if(mapCount.get("purchaseCount")!=null) {
				purchaseCount = new BigDecimal(mapCount.get("purchaseCount").toString());
			}
			if(mapCount.get("feedCount")!=null) {
				allFeedCount = new BigDecimal(mapCount.get("feedCount").toString());
			}
			if(mapCount.get("stockCount")!=null) {
				notOrderMaterialCount = new BigDecimal(mapCount.get("stockCount").toString());
			} 
			//可领取库存数
			materialReceiveCount = purchaseCount.add(notOrderMaterialCount).subtract(allFeedCount);
			if(materialReceiveCount.subtract(bigCount).doubleValue()<0) {
				throw new ServiceException("库存不足或该物料数量被投料单占用");
			}
		}else if(wiodb.getType()==7){
			throw new ServiceException("请至我的报工页面修改！");
		}else if(wiodb.getType()==9){
			CompanyMaterialTableBean cmtb=companyMaterialMapper.getCompanyMaterialTableByMaterialCode(map);
			if(cmtb==null) {
				throw new ServiceException("物料信息为空异常");
			}
			//库存数量
			BigDecimal materialReceiveCount =new BigDecimal("0.0");
			//采购数
			BigDecimal purchaseCount = new BigDecimal("0.0");
			//排除订单的库存数
			BigDecimal notOrderMaterialCount = new BigDecimal("0.0");
			//所有投料数
			BigDecimal allFeedCount = new BigDecimal("0.0");
			Map<String, Double> mapCount =  otherWarehouseMapper.getCountResult(wiodb.getMaterialCode(),map.get("loginCompany").toString());
			if(mapCount.get("purchaseCount")!=null) {
				purchaseCount = new BigDecimal(mapCount.get("purchaseCount").toString());
			}
			if(mapCount.get("feedCount")!=null) {
				allFeedCount = new BigDecimal(mapCount.get("feedCount").toString());
			}
			if(mapCount.get("stockCount")!=null) {
				notOrderMaterialCount = new BigDecimal(mapCount.get("stockCount").toString());
			}
			//可领取库存数
			materialReceiveCount = purchaseCount.add(notOrderMaterialCount).subtract(allFeedCount);
			if(materialReceiveCount.subtract(bigCount).doubleValue()<0) {
				throw new ServiceException("库存不足或该物料数量被投料单占用");
			}
		}else {
			throw new ServiceException("请选择正确的出库类型");
		}
		wiodb.setStatus(0);//修改状态为未审批
		wiodb.setCount(count);//设置数量
		xx.add(wiodb);
		map.put("listIn", xx);
		companyMaterialMapper.updateWarehouseInOutCount(map);
	}
	
	public void updateWarehouseInOutCount(Map map) {
		companyMaterialMapper.updateWarehouseInOutCount(map);
	}

	//删除出入库信息 
	public void deleteWarehouseInOut(Map map) throws ServiceException {
		List<WarehouseInOutDetailBean> xx=new ArrayList<WarehouseInOutDetailBean>();
		WarehouseInOutDetailBean wiodb=companyMaterialMapper.getInWarehourseByIdOne(map.get("id").toString());
		if(wiodb ==null) {
			throw new ServiceException("该出入库单已经删除,请勿再次操作");
		} 
		if(wiodb.getStatus()!=0) {
			throw new ServiceException("该出入库单已经审核,无法删除");
		}  
		if(wiodb.getType()==1) {//订单采购入库
			List<PurchaseOrderDetailBean> list=new ArrayList<PurchaseOrderDetailBean>();
			PurchaseOrderDetailBean podb=companyMaterialMapper.getPurchaseOrderDetailById(wiodb.getPurcharseOrderId());
			podb.setInCount(podb.getInCount()-wiodb.getCount());
			podb.setIsFinish(0);
			list.add(podb);
			companyMaterialMapper.updatePurchaseOrderDetail(list);
		}else if(wiodb.getType()==3) {//库存采购入库
			PurchaseDetailBean podb=companyMaterialMapper.getPurchaseDetailById(wiodb.getPurcharseOrderId());
			podb.setInCount(podb.getInCount()-wiodb.getCount());
			podb.setIsFinish(0);
		    companyMaterialMapper.updatePurchaseDetailOne(podb);
		}else if(wiodb.getType()==4){//无采购单入库,直接删除
			
		}else if(wiodb.getType()==2){//投料单领料
			List<FeedOrderDetailBean> feedList=new ArrayList<FeedOrderDetailBean>();
			FeedOrderDetailBean feedDeatil=orderService.getFeedOrderDetailOneById(wiodb.getFeedOrder());
			map.put("materialCode", wiodb.getMaterialCode());
			CompanyMaterialTableBean cmtb=companyMaterialMapper.getCompanyMaterialTableByMaterialCode(map);
			if(cmtb==null) {
				throw new ServiceException("物料信息为空");
			}
			//出入库单位和库存单位相同
			if(wiodb.getInOutUnit().equals(cmtb.getUnit())) {
				//物料单位领料数
				BigDecimal bigFeedReceiveCount = new BigDecimal(feedDeatil.getReceiveCount().toString());
				//物料单位出库数
				BigDecimal bigOutCount = new BigDecimal(wiodb.getCount().toString());
				feedDeatil.setReceiveCount(bigFeedReceiveCount.subtract(bigOutCount).doubleValue());
				feedDeatil.setIsReceiveFinish(0);
			}else {
				//生产单位领料数
				BigDecimal bigFeedReceiveCount = new BigDecimal(feedDeatil.getProductionUnitReceiveCount().toString());
				//生产单位出库数
				BigDecimal bigOutCount = new BigDecimal(wiodb.getCount().toString());
				feedDeatil.setProductionUnitReceiveCount(bigFeedReceiveCount.subtract(bigOutCount).doubleValue());
				feedDeatil.setIsReceiveFinish(0);
			}
			Map paramMap=new HashMap();
			feedList.add(feedDeatil);
		    //修改投料单明细的领料数
		    paramMap.put("feedList", feedList);
		    companyMaterialMapper.updateFeedOrderDetailReceive(paramMap);
		}else if(wiodb.getType()==5 || wiodb.getType()==9) {//无投料单出库  直接删除
			 
		}else if(wiodb.getType()==7) {//如果是车间交接至仓库
			workshopService.deleteReportByOtherId(wiodb.getId());
		}else {
			throw new ServiceException("请选择正确的出入库类型");
		}
		xx.add(wiodb);
		map.put("listIn", xx);
		companyMaterialMapper.deletePurchaseDetail(map);
	}
	
	public void deletePurchaseDetail (Map map) {
		companyMaterialMapper.deletePurchaseDetail(map);
	}
	
	/**
	 * 修改投料单状态
	 * @param map
	 */
	public void updateFeedOrderDetailReceive(Map map) {
		companyMaterialMapper.updateFeedOrderDetailReceive(map);
	}
	
	
	/**
	 * 批量添加公司物料表通过上传文件 at 2018-04-01 by 李斌
	 * @param multipartFile
	 * @param myUser
	 * @return
	 * @throws ServiceException 
	 * @throws IOException 
	 * @throws Exception 
	 */ 
	public List<String> addWarehouseByFile(MultipartFile filename, MyUser myUser) throws ServiceException, IOException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		//保存成功的List
		List<CompanyMaterialTableBean> companyMaterialList = new ArrayList<CompanyMaterialTableBean>();
		//获取excel文件名
		String excelName = filename.getOriginalFilename();
		//判断后缀名
		boolean suffixName = excelName.endsWith(".xlsx");
		if(!suffixName){
			throw new ServiceException("请按照模板上传xlsx格式文件");
		}
		XSSFWorkbook xwb=null;
		try {
			xwb=new XSSFWorkbook(filename.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		XSSFSheet sheet = xwb.getSheetAt(0);
		int rowNum = sheet.getLastRowNum();//得到有效的行数
		int colNum = sheet.getRow(0).getLastCellNum();
		Assert.isTrue(rowNum<303, "每次最多导入三百条物料");
		for (int rowIndex = 2; rowIndex <=rowNum; rowIndex++) {
			CompanyMaterialTableBean companyMaterialTableBean = new CompanyMaterialTableBean();
			XSSFRow row=sheet.getRow(rowIndex);
			for(int cellIndex=0;cellIndex<colNum;cellIndex++){
				XSSFCell cell=row.getCell(cellIndex);
				for(int i=0;i<colNum;i++) {
					if(row.getCell(i)!=null) { 
						row.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
					}
				}
				switch(cellIndex){
					case 0:companyMaterialTableBean.setMaterialName(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 1:companyMaterialTableBean.setModel(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 2:companyMaterialTableBean.setStatus("使用");//cell==null?"":cell.getStringCellValue().trim()
					break;
					case 3:companyMaterialTableBean.setDefaultWarehouse(cell==null?"":cell.getStringCellValue().trim());
					break; 
					case 4://仓位
						companyMaterialTableBean.setPositions(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 5:companyMaterialTableBean.setProviderName(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 6:companyMaterialTableBean.setMaterialType(cell==null?"":cell.getStringCellValue()==null?"":cell.getStringCellValue().trim());
					break;
					case 7:companyMaterialTableBean.setUnit(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 8:companyMaterialTableBean.setUnitPrice(Double.valueOf(cell==null?"0":cell.getStringCellValue().trim()==""?"0.0":cell.getStringCellValue()));	
					break;
					case 9:companyMaterialTableBean.setIsEquals(Integer.valueOf(cell==null?"0":cell.getStringCellValue().trim()==""?"0":cell.getStringCellValue().trim()));
					break; 
					case 10:companyMaterialTableBean.setColor(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 11:companyMaterialTableBean.setColorDescription(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 12:companyMaterialTableBean.setProcurementCycles(Integer.valueOf(cell==null?"0":cell.getStringCellValue().trim()==""?"0":cell.getStringCellValue().trim()));
					break;
					case 13:companyMaterialTableBean.setTransmittance(Double.valueOf(cell==null?"0":cell.getStringCellValue().trim()==""?"0":cell.getStringCellValue().trim()));
					break;
					case 14:companyMaterialTableBean.setSafetyStockMax(Double.valueOf(cell==null?"0":cell.getStringCellValue().trim()==""?"0":cell.getStringCellValue().trim()));
					break;
					case 15:companyMaterialTableBean.setSafetyStockMin(Double.valueOf(cell==null?"0":cell.getStringCellValue().trim()==""?"0":cell.getStringCellValue().trim()));
					break;
					case 16:companyMaterialTableBean.setProviderNo(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 17:companyMaterialTableBean.setMaterial(cell==null?"":cell.getStringCellValue().trim());
					break;
					case 18:companyMaterialTableBean.setCount(Double.valueOf(cell==null?"0.0":cell.getStringCellValue().trim()));
				}
			} 
			
			if(companyMaterialTableBean.getMaterialName()==null||companyMaterialTableBean.getMaterialName().trim().equals("")) {
				throw new ServiceException("物料名称不能为空");
			}
			if(companyMaterialTableBean.getProviderName()==null||companyMaterialTableBean.getProviderName().trim().equals("")) {
				throw new ServiceException("供应商名称不能为空");
			}
			/*if(companyMaterialTableBean.getMaterialType()==null||companyMaterialTableBean.getMaterialType().trim().equals("")) {
				throw new ServiceException("物料类型不能为空");
			}*/
			if(companyMaterialTableBean.getDefaultWarehouse()==null||companyMaterialTableBean.getDefaultWarehouse().trim().equals("")) {
				throw new ServiceException("仓库不能为空");
			}
			if(companyMaterialTableBean.getModel()==null||companyMaterialTableBean.getModel().trim().equals("")) {
				throw new ServiceException("规格不能为空");
			}
			if(companyMaterialTableBean.getUnit()==null||companyMaterialTableBean.getUnit().trim().equals("")) {
				throw new ServiceException("单位不能为空");
			}
			if(!"镜片".equals(companyMaterialTableBean.getMaterialType())) {
				companyMaterialTableBean.setTransmittance(null);
			}
			if("付".equals(companyMaterialTableBean.getUnit())) {
				companyMaterialTableBean.setIsEquals(1);
			}else {
				companyMaterialTableBean.setIsEquals(0);
			}
			int unitCount =  basicDataMapper.getCompanyMaterialUnitByUnit(companyMaterialTableBean);
			if(unitCount<1) {
				throw new ServiceException(companyMaterialTableBean.getUnit()+",单位名称不在公共单位表中");
			}
			companyMaterialTableBean.setMaterialCode(basicDataService.setCompanyMaterialCode(companyMaterialTableBean.getProviderName(), companyMaterialTableBean.getMaterialName()));
			companyMaterialTableBean.setCompany(myUser.getCompany());
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("materialName",companyMaterialTableBean.getMaterialName());
			paramMap.put("model", companyMaterialTableBean.getModel());
			paramMap.put("providerName", companyMaterialTableBean.getProviderName());
			paramMap.put("color", companyMaterialTableBean.getColor());
			paramMap.put("loginCompany",myUser.getCompany()); 
			/*Map<String,String> mateiralTypeMap = new HashMap<String,String>();
			mateiralTypeMap.put("loginCompany", myUser.getCompany());
			mateiralTypeMap.put("materialType", companyMaterialTableBean.getMaterialType());
			mateiralTypeMap.put("status","1");
			CompanyMaterialTypeBean materialTreeBean =companyMaterialTypeService.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
			if(materialTreeBean.getIsReadColor()==2) {
				paramMap.put("color", "");
				companyMaterialTableBean.setColor("");
				companyMaterialTableBean.setColorDescription("");
			}*/
			//查询公司物料表中是否有相同的物料数据.不用物料代码查
			List<CompanyMaterialTableBean> oldMaterialList = basicDataMapper.getUniqueCompanyMaterialByDetail(paramMap);
			if(oldMaterialList!= null && oldMaterialList.size()>0) {
				continue;
			}else {   
				companyMaterialTableBean.setCreater(myUser.getUserName());
				companyMaterialTableBean.setCreationTime(sdf.format(new Date()));
				companyMaterialTableBean.setLastModifyTime(sdf.format(new Date()));;
				companyMaterialTableBean.setLastModifier(myUser.getUserName());
				Map customerParam = new HashMap();
				customerParam.put("loginCompany",myUser.getCompany());
				customerParam.put("customerName",companyMaterialTableBean.getProviderName());
				List<CustomerBean> customerList = basicDataMapper.getCustomerListByCustomerName(customerParam);
				if(customerList==null||customerList.size()<1) {
					CustomerBean customerBean = new CustomerBean();
					customerBean.setCustomerCode(companyMaterialTableBean.getProviderName());
					customerBean.setCompany(myUser.getCompany());
					customerBean.setCreater(myUser.getUserName());
					customerBean.setCreationTime(sdf.format(new Date()));
					customerBean.setCustomerName(companyMaterialTableBean.getProviderName());
					customerBean.setStatus("使用");
					customerBean.setType(1);
					basicDataMapper.insertCustomer(customerBean); 
				}
				//插入仓位
				if(companyMaterialTableBean.getPositions()!=null&&!"".equals(companyMaterialTableBean.getPositions())) {
					List<MaterialPositionBean> materialPositionList = new ArrayList<MaterialPositionBean>();
					MaterialPositionBean materialPositionBean = new MaterialPositionBean();
					materialPositionBean.setCompany(companyMaterialTableBean.getCompany());
					materialPositionBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
					materialPositionBean.setPosition(companyMaterialTableBean.getPositions());
					materialPositionList.add(materialPositionBean);
					Map<String,Object> map = new HashMap<>();
					map.put("materialPositionList", materialPositionList);
					materialPositionMapper.addMaterialPositionList(map);
				}
				companyMaterialList.add(companyMaterialTableBean);
				companyMaterialMapper.addWarehouseByFile(companyMaterialList);
				companyMaterialList.clear();
				if(companyMaterialTableBean.getCount()>0) {
					List<WarehouseInOutDetailBean> inOutList = new ArrayList<WarehouseInOutDetailBean>();
					WarehouseInOutDetailBean warehouseInOutDetailBean = new WarehouseInOutDetailBean();
					String rkId = DingTalkMapper.getApprovalNo("RK");
					warehouseInOutDetailBean.setId(rkId);
					warehouseInOutDetailBean.setType(8);//模板导入入库类型
					warehouseInOutDetailBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
					warehouseInOutDetailBean.setCount(companyMaterialTableBean.getCount());
					warehouseInOutDetailBean.setPurcharseOrderId("模板导入入库");
					warehouseInOutDetailBean.setCreateUser(myUser.getUserId());
					warehouseInOutDetailBean.setCreateTime(sdf.format(new Date()));
					warehouseInOutDetailBean.setStatus(1); 
					warehouseInOutDetailBean.setApprovalUser(myUser.getUserId());
					warehouseInOutDetailBean.setApprovalTime(sdf.format(new Date())); 
					warehouseInOutDetailBean.setMaterialName(companyMaterialTableBean.getMaterialName());
					warehouseInOutDetailBean.setColor(companyMaterialTableBean.getColor());
					warehouseInOutDetailBean.setProviderName(companyMaterialTableBean.getProviderName());
					warehouseInOutDetailBean.setModel(companyMaterialTableBean.getModel());
					warehouseInOutDetailBean.setColorDescription(companyMaterialTableBean.getColorDescription());
					warehouseInOutDetailBean.setCompany(myUser.getCompany());
					warehouseInOutDetailBean.setWarehouseType(4);
					warehouseInOutDetailBean.setInOutUnit(companyMaterialTableBean.getUnit());
					warehouseInOutDetailBean.setInCountPrice(companyMaterialTableBean.getUnitPrice());
					inOutList.add(warehouseInOutDetailBean);
					if(inOutList.size()>0) {
						companyMaterialMapper.insertInOutRecode(inOutList);
					}
					companyMaterialTableBean.setIsTemplateImport(true);
				}
				customerParam.put("companyMaterialTableBean", companyMaterialTableBean);
				basicDataService.addCompanyMaterialCountOnMaterial(customerParam);
			} 
		} 
		return null;
	}
	/**
	 * 批量导入物料
	 * @param filename
	 * @param myUser
	 * @return
	 * @throws ServiceException
	 * @throws IOException
	 */
	public Boolean addWarehouseForShopByBatch(MyUser myUser,List<CompanyMaterialTableBean> beans) throws ServiceException, IOException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		//保存成功的List
		List<CompanyMaterialTableBean> companyMaterialList = new ArrayList<CompanyMaterialTableBean>();
		
		for (int i = 0; i < beans.size(); i++) {
			CompanyMaterialTableBean companyMaterialTableBean = new CompanyMaterialTableBean();
			companyMaterialTableBean.setMaterialName(beans.get(i).getMaterialName());//物料名称
			companyMaterialTableBean.setModel(beans.get(i).getModel());//规格型号
			companyMaterialTableBean.setStatus(beans.get(i).getStatus());//状态
			companyMaterialTableBean.setDefaultWarehouse(beans.get(i).getDefaultWarehouse());//默认仓库
			companyMaterialTableBean.setProviderName(beans.get(i).getProviderName());//供应商名称
			companyMaterialTableBean.setMaterialType(beans.get(i).getMaterialType());//物料类型
			companyMaterialTableBean.setUnit(beans.get(i).getUnit());//单位
			companyMaterialTableBean.setUnitPrice(beans.get(i).getUnitPrice());//单价
			companyMaterialTableBean.setIsEquals(beans.get(i).getIsEquals());//计价单位是否与生产单位相同 1=是  0=否
			companyMaterialTableBean.setColor(beans.get(i).getColor());//色号
			companyMaterialTableBean.setColorDescription(beans.get(i).getColorDescription());//色号描述
			companyMaterialTableBean.setProcurementCycles(beans.get(i).getProcurementCycles());//采购周期
			companyMaterialTableBean.setTransmittance(beans.get(i).getTransmittance());//透光率
			companyMaterialTableBean.setSafetyStockMax(beans.get(i).getSafetyStockMax());//库存上限
			companyMaterialTableBean.setSafetyStockMin(beans.get(i).getSafetyStockMin());//库存下限
			companyMaterialTableBean.setProviderNo(beans.get(i).getProviderNo());//供方编号
			companyMaterialTableBean.setMaterial(beans.get(i).getMaterial());//材质
			companyMaterialTableBean.setCount(beans.get(i).getCount());//数量
			companyMaterialTableBean.setImg(beans.get(i).getImg());//图片一
			companyMaterialTableBean.setImgTwo(beans.get(i).getImgTwo());//图片二
			companyMaterialTableBean.setImgThree(beans.get(i).getImgThree());//图片三
			companyMaterialTableBean.setImgFour(beans.get(i).getImgFour());//图片四
			/**
			 * 物料代码
			 */
			companyMaterialTableBean.setMaterialCode(beans.get(i).getMaterialCode());
			companyMaterialTableBean.setCompany(myUser.getCompany());//公司
			
			if(companyMaterialTableBean.getMaterialName()==null||companyMaterialTableBean.getMaterialName().trim().equals("")) {
				throw new ServiceException("物料名称不能为空");
			}
			if(companyMaterialTableBean.getProviderName()==null||companyMaterialTableBean.getProviderName().trim().equals("")) {
				throw new ServiceException("供应商名称不能为空");
			}
			
			if(companyMaterialTableBean.getDefaultWarehouse()==null||companyMaterialTableBean.getDefaultWarehouse().trim().equals("")) {
				throw new ServiceException("仓库不能为空");
			}
			if(companyMaterialTableBean.getModel()==null||companyMaterialTableBean.getModel().trim().equals("")) {
				throw new ServiceException("规格不能为空");
			}
			if(companyMaterialTableBean.getUnit()==null||companyMaterialTableBean.getUnit().trim().equals("")) {
				throw new ServiceException("单位不能为空");
			}
			if(companyMaterialTableBean.getMaterialCode()==null||companyMaterialTableBean.getMaterialCode().trim().equals("")) {
				throw new ServiceException("物料代码不能为空");
			}
			if(!"镜片".equals(companyMaterialTableBean.getMaterialType())) {
				companyMaterialTableBean.setTransmittance(null);
			}
			if("付".equals(companyMaterialTableBean.getUnit())) {
				companyMaterialTableBean.setIsEquals(1);
			}else {
				companyMaterialTableBean.setIsEquals(0);
			}
			int unitCount =  basicDataMapper.getCompanyMaterialUnitByUnit(companyMaterialTableBean);
			if(unitCount<1) {
				throw new ServiceException(companyMaterialTableBean.getUnit()+",单位名称不在公共单位表中");
			}
			/**
			 * 区别
			 */
			/*if(companyMaterialTableBean.getMaterialType()==null||companyMaterialTableBean.getMaterialType().trim().equals("")) {
				throw new ServiceException("物料类型不能为空");
			}*/
			/**
			 * 查询物料是否读取颜色
			 */
			Map<String,String> mateiralTypeMap = new HashMap<String,String>();
			mateiralTypeMap.put("loginCompany", myUser.getCompany());
			mateiralTypeMap.put("materialType", companyMaterialTableBean.getMaterialType());
			mateiralTypeMap.put("status","1");
			//CompanyMaterialTypeBean materialTreeBean =companyMaterialTypeService.getCompanyMaterialTypeByMateiralType(mateiralTypeMap);
			/**
			 * 查询是否公司物料表中是否已经存在
			 */
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("materialName",companyMaterialTableBean.getMaterialName());
			paramMap.put("model", companyMaterialTableBean.getModel());
			paramMap.put("providerName", companyMaterialTableBean.getProviderName());
			paramMap.put("color", companyMaterialTableBean.getColor());
			paramMap.put("loginCompany",myUser.getCompany()); 
			/*if(materialTreeBean.getIsReadColor()==2) {
				paramMap.put("color", "");
				companyMaterialTableBean.setColor("");
				companyMaterialTableBean.setColorDescription("");
			}*/
			/**
			 * 区别
			 */
			if(companyMaterialTableBean.getColor()==null||"".equals(companyMaterialTableBean.getColor())) {
				companyMaterialTableBean.setColor("");
				companyMaterialTableBean.setColorDescription("");
				paramMap.put("color", "");
			}
			List<CompanyMaterialTableBean> oldMaterialList = basicDataMapper.getUniqueCompanyMaterialByDetail(paramMap);
			if(oldMaterialList!= null && oldMaterialList.size()>0) {
				continue;
			}else {
				companyMaterialTableBean.setCreater(myUser.getUserName());
				companyMaterialTableBean.setCreationTime(sdf.format(new Date()));
				companyMaterialTableBean.setLastModifyTime(sdf.format(new Date()));;
				companyMaterialTableBean.setLastModifier(myUser.getUserName());
				/**
				 * 添加到集合中
				 */
				companyMaterialList.add(companyMaterialTableBean);
			}
		}
		/**
		 * 批量导入公司物料表
		 */
		companyMaterialMapper.addWarehouseByFile(companyMaterialList);
		companyMaterialList.forEach(bean -> {
            System.out.println(bean.getId());
            //异步同步到百度图片库
    		basicDataService.synImgsToBaidu(bean, myUser,"0");
        });
		return true;
	}

//	通过物料bean获取物料信息
	List<CompanyMaterialTableBean> getCompanyMaterialByBean(CompanyMaterialTableBean xx){
		return companyMaterialMapper.getCompanyMaterialByBean(xx);
	}
	
//	通过物料map获取物料信息
	public List<CompanyMaterialTableBean> getCompanyMaterialByMap(Map map){
		map.put("company", map.get("loginCompany").toString());
		return companyMaterialMapper.getCompanyMaterialByMap(map);
	}
	
	
//	通过物料map获取物料信息
	public List<CompanyMaterialTableBean> getVagueCompanyMaterialByMap(Map map){
		return companyMaterialMapper.getVagueCompanyMaterialByMap(map);
	}

	/**
	 * 获取订单编号用于采购单入库
	* @date 2018年4月18日 下午6:58:44 
	* @author 李斌
	* @return void 
	* @throws
	 */  
	public List<String> getOrderIdOnWarehouseIn(Map map) {
		List<String> orderIds = companyMaterialMapper.getOrderIdOnWarehouseIn(map);
		if(orderIds!=null&&orderIds.size()>0) {
			//利用set的特性去重复
			Set<String> sets = new HashSet<String>(orderIds);
			//清除
			orderIds.clear();
			orderIds.addAll(sets);
		} 
		return orderIds;
	}

	
	/**
	 * 获取工厂型号用于采购单入库
	* @date 2018年4月18日 下午7:33:44 
	* @author 李斌
	* @return Object 
	* @throws
	 */
	public List<String> getFactoryNoOnWarehouseIn(Map map) {
		List<String> factoryNos = companyMaterialMapper.getFactoryNoOnWarehouseIn(map);
		if(factoryNos!=null&&factoryNos.size()>0) {
			//利用set的特性去重复
			Set<String> sets = new HashSet<String>(factoryNos);
			//清除
			factoryNos.clear();
			factoryNos.addAll(sets);
		} 
		return factoryNos;
	}
	
	/**
	 * 获取客户型号用于采购单入库
	* @date 2018年4月18日 下午7:43:37 
	* @author 李斌
	* @return Object 
	* @throws
	 */
	public List<String> getArticleNoOnWarehouseIn(Map map) {
		List<String> articleNos = companyMaterialMapper.getArticleNoOnWarehouseIn(map);
		if(articleNos!=null&&articleNos.size()>0) {
			//利用set的特性去重复
			Set<String> sets = new HashSet<String>(articleNos);
			//清除
			articleNos.clear();
			articleNos.addAll(sets);
		} 
		return articleNos;
	}

	//获取分页数据
	public DatatablesViewPageBean<CompanyMaterialTableBean> getVagueCompanyMaterialByMapToPage(Map map) {
		int count=0;
		CompanyBean companyBean = companyMapper.getCompany(map);
		DatatablesViewPageBean<CompanyMaterialTableBean> dtcpb=new DatatablesViewPageBean<CompanyMaterialTableBean>();
		List<CompanyMaterialTableBean> companyMaterialTableBeans = companyMaterialMapper.getVagueCompanyMaterialByMap(map);
		//获取公司物料仓位，一个物料有多个
		List<MaterialPositionBean> materialPositionList = companyMaterialCountService.getMaterialPositionList(map);
		if(materialPositionList != null && materialPositionList.size() > 0) {
			for(CompanyMaterialTableBean companyMaterialCount:companyMaterialTableBeans) {
				//设置物料仓位
				List<String> positionList = materialPositionList.stream().filter(po->po.getMaterialCode().equals(companyMaterialCount.getMaterialCode())).map(MaterialPositionBean::getPosition).collect(Collectors.toList());
				companyMaterialCount.setPositionList(positionList);
			}
		}
		dtcpb.setReturnData(companyMaterialTableBeans);
		count=companyMaterialMapper.getVagueCompanyMaterialByMapCount(map);
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		dtcpb.setCode(companyBean.getCanUpdatePriceAndUnit());
		return dtcpb;
	}

	//无采购单入库
	public String savdInWarehouseNotPurchase(Map map,HttpServletRequest request) throws ServiceException {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		String time=sdf.format(new Date());
		String metailArray=map.get("array").toString();
		JSONArray jsonArray=JSONArray.fromObject(metailArray);
		//前台传过来的物料集合
		List<CompanyMaterialTableBean> listCmtb=(List<CompanyMaterialTableBean>) JSONArray.toCollection(jsonArray, CompanyMaterialTableBean.class);
		//自动生成的出入库记录
		List<WarehouseInOutDetailBean> inOutList=new ArrayList<WarehouseInOutDetailBean>();
	    //要修改的物料集合
		List<CompanyMaterialTableBean> listCompanyMaterial=new ArrayList<CompanyMaterialTableBean>();
		//发送消息用的集合
		Map<String,Object> materialParam = new HashMap<String,Object>(); 
		materialParam.put("loginCompany", map.get("loginCompany"));
		List<CompanyMaterialTableBean> message = new ArrayList<CompanyMaterialTableBean>();
		List<String> idList = new ArrayList<String>();
		for(CompanyMaterialTableBean cmtb:listCmtb) {
	    	if(cmtb.getType()==4) {//无采购单 不增加物料入库
	    		Double count = cmtb.getCount()==null?0.0:cmtb.getCount();
			    WarehouseInOutDetailBean warehouseInOutDetailBean=new WarehouseInOutDetailBean();
			    warehouseInOutDetailBean.setCount(count);//入库数量
			    warehouseInOutDetailBean.setCreateTime(time);//入库时间
			    warehouseInOutDetailBean.setCreateUser(map.get("loginUserId").toString());//采购人
			    String rkId = DingTalkMapper.getApprovalNo("RK");
			    warehouseInOutDetailBean.setId(rkId);
			    warehouseInOutDetailBean.setMaterialCode(cmtb.getMaterialCode());//物料代码
			    warehouseInOutDetailBean.setPurcharseOrderId("无采购单不增物料入库");//入库投料单采购单对应表Id
			    warehouseInOutDetailBean.setType(4);//类型1为订单采购入库   2为出库 3 为库存才采购单入库
			    warehouseInOutDetailBean.setPosition(cmtb.getPositions());
			    warehouseInOutDetailBean.setMaterialName(cmtb.getMaterialName());
			    warehouseInOutDetailBean.setColor(cmtb.getColor());
			    warehouseInOutDetailBean.setModel(cmtb.getModel());
			    warehouseInOutDetailBean.setProviderName(cmtb.getProviderName());
			    warehouseInOutDetailBean.setRemark(cmtb.getRemark());
			    warehouseInOutDetailBean.setOutCountPrice(cmtb.getOutCountPrice());
			    if(cmtb.getInCountPrice()!=null) {
			    	warehouseInOutDetailBean.setInCountPrice(cmtb.getInCountPrice());
			    }
			    //如果制单人和接受人是同一个人，默认审批，修改库存数
		    	warehouseInOutDetailBean.setStatus(0); 
		    	materialParam.put("materialCode",warehouseInOutDetailBean.getMaterialCode());//getupdateCompanyMaterialByCode
		    	CompanyMaterialTableBean companyMaterialTableBean = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(materialParam);
		    	if(companyMaterialTableBean!=null) {
		    		if("禁用".equals(companyMaterialTableBean.getStatus())) {
		    			throw new ServiceException("该物料已禁用,入库失败");
		    		}
		    		message.add(companyMaterialTableBean);
		    	}else {
		    		throw new ServiceException("无物料信息异常");
		    	}
			    //入库单位
			    warehouseInOutDetailBean.setInOutUnit(companyMaterialTableBean.getUnit());
			    warehouseInOutDetailBean.setWarehouseInType(4);//采购入库类型 1订单采购入库 2库存采购入库 无采购单入库
			    warehouseInOutDetailBean.setCompany(map.get("loginCompany").toString());
			    inOutList.add(warehouseInOutDetailBean);
			    idList.add(warehouseInOutDetailBean.getId());
	    	} 
	    	//插入入库记录 
		    if(inOutList !=null && inOutList.size()>0) {
		    	companyMaterialMapper.insertInOutRecode(inOutList);
		    	inOutList.clear();
		    }
	    }
	    
	    /**
	     * 发消息提示需审核
	     */  
		String queryCondition = "?ids="+idList.toString().substring(1,idList.toString().length()-1).replace(" ","");
		return this.sendWechatMessage("无采购入库单", 2, "无采购入库待审批通知", sdf.format(new Date()), map, RedirectUrlUtil.queryWarehouse+queryCondition, 1);
	}
	
	/**
	 * 通过物料代码获取出入库明细
	* @date 2018年5月16日 下午8:02:13 
	* @author 李斌
	* @return Object 
	* @throws
	 */
	public List<WarehouseInOutDetailBean> getWarehouseInOutByMaterialCode(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return companyMaterialMapper.getWarehouseInOutByMaterialCode(map);
	}
	
	/**
	 * 发送安全库存下限警报
	 * title 消息头
	 * bodyMessage 消息体
	 * dataStrig 时间
	 * 请求参数集 paramMap
	* @date 2018年7月26日 上午9:21:51 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String sendSafetyStockMinMessage(String title ,String bodyMessage,String dateString,Map<String,Object> paramMap,String pageType,String peopleMessageType,int WarehouseType) {
		//获取异常消息推送人 
		List<String> userIds=weChatToMessageService.getWeChatNewsUserIdListByParam(paramMap.get("loginCompany").toString(),null,null, peopleMessageType);
		if(userIds.size()<1) {
			return "未设置库存下限消息接收人员";
		} 
		paramMap.put("userIds", userIds);
		List<String> openIdList=weiXinPeopleService.getOpenIdByUserIds(paramMap);
		if(null == openIdList || openIdList.size()<=0) {
			return " 库存下限消息接收人员未关联微信,无法收到审核提醒,请人工通知库存不足!";
		} 
		String accessToken = null;
		try {
			accessToken = weiXinService.getAccessToken(null);
		} catch (RuntimeException e) {
			return "无法获取accessToken";  
		}  
		int flag = 0;
		String exceptionType = "";
		if("8".equals(peopleMessageType)) {
			exceptionType = "库存不足";
		}else if("9".equals(peopleMessageType)) {
			if(WarehouseType==1) {
				exceptionType = "订单采购单入库结算";
			}else if(WarehouseType ==2) {
				exceptionType = "库存采购单入库结算"; 
			}
			
		}
		for(String openId:openIdList) { 
			com.alibaba.fastjson.JSONObject data = WeixinTemplateList.packJsonToWarningNotice(title, exceptionType, dateString, bodyMessage, null, null, null, null);
			String xx=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.exceptionTemplateID, WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+pageType, data, accessToken);
			if(!"success".equals(xx)) {
				flag ++;
			}else {
				flag = 0; 
				break; 
			}
		} 
		
		if(flag==0) {
			return "";
		}else { 
			return  "友情提示：采购或仓库人员未关联微信,无法收到库存报警,请人工通知审核!";
		}
	}
	
	/**
	 * 发送消息 title 消息头 orderType 
	 * 订单类型 1 采购单 2 出入库单 
	 * 消息体  dataString 
	 * 时间字符串 
	 * paramMap用户信息参数集合 
	 * pageType 页面类型 具体看userCountroller
	 * warehouseType 具体类型如(入库 1,出库 2)
	* @date 2018年6月2日 上午9:22:55 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String sendWechatMessage(String titel,int orderType,String bodyMessage,String dateString,Map paramMap,String pageType,int warehouseType) throws ServiceException {
		try { 
			bodyMessage=bodyMessage+"(免登录查看)";
			List<String> userIds = null;
			String orderName = null; 
			paramMap.put("name", paramMap.get("loginUserName"));
			UserBean userBean = userService.getUserByName(paramMap);
			if(orderType==1) {//采购单
				paramMap.put("type",4);
				userIds = approvalService.getApprovalUserIdByLoginUserId(paramMap);
				orderName = "采购单";
			}else if(orderType==2) {//出入库
				paramMap.put("type",6); 
				userIds = approvalService.getApprovalUserIdByLoginUserId(paramMap);
				if(warehouseType==1) { //入库
					orderName = "入库单";
				}else if(warehouseType==2) {//出库
					orderName = "出库单";
				}else if(warehouseType == 3) {//退货
					orderName = "退货单";
				}else if(warehouseType == 4) {//返料
					String userId = paramMap.get("pickingPeople").toString();
					userIds = new ArrayList<String>();
					userIds.add(userId);
					orderName = "返料单";
				}
			}else if(orderType==3) { 
				paramMap.put("type",3); 
				userIds = approvalService.getApprovalUserIdByLoginUserId(paramMap);
				orderName = "投料单";
			}else if(orderType==4) {
				String userId = paramMap.get("pickingPeople").toString();
				userIds = new ArrayList<String>();
				userIds.add(userId);
				orderName = "发料单";
			}else if(orderType == 5) {
				orderName = "外协";
				List<String> putOutUserList = workshopService.getPutOutApprovalUserName(paramMap);
				if(putOutUserList !=null && putOutUserList.size()>0) {
					paramMap.put("userNames", putOutUserList);
					userIds = userMapper.getUserIdsByNames(paramMap);
				}
			}
			if(null == userIds ||userIds.size()<1) {
				if(null==orderName) {
					orderName="";
				}
				return "    友情提示："+orderName+"未设置审核人!";
			}
			paramMap.put("userIds", userIds);
			List<String> openIdList=weiXinPeopleService.getOpenIdByUserIds(paramMap);
			if(null == openIdList || openIdList.size()<=0) {
				return "    友情提示："+orderName+"审核人未关联微信,无法收到审核提醒,请人工通知审核!";
			}
			String accessToken = null;
			try {
				accessToken = weiXinService.getAccessToken(null);
			} catch (RuntimeException e) {
				return "无法获取accessToken";  
			} 
			int flag = 0;
			for(String openId:openIdList) {
				com.alibaba.fastjson.JSONObject json=WeixinTemplateList.packJsonWatiApproval(titel, orderName, paramMap.get("loginUserName").toString(), userBean.getPhone(),dateString,bodyMessage , null, null, null, null, null, null, null, null);
				String xx=WeixinTemplateSender.sendWechatmsgToUser(openId, WeiXinParamesUtil.watiApprovalTemplateID, WeiXinParamesUtil.messageLink+"?loginToken="+openId+"&pageType="+pageType, json, accessToken);
				if(!"success".equals(xx)) {
					flag ++;
				}else {
					flag = 0; 
				}
			} 
			
			if(flag!=0) {
				return  "友情提示："+orderName+"审核人未关联微信,无法收到审核提醒,请人工通知审核!";
			}else {
				return "";
			}
		} catch (Exception e) { 
			return "微信信息发送失败,请人工通知";
		}
	}
	
	//投料单出库报工至车间
	public String getReportDataByWarehouse(WarehouseInOutDetailBean warehouse,MyUser myUser,String dateString) throws ServiceException {
		Map<String, Object> map = new HashMap<String,Object>();
		//获取投料单明细 
		FeedOrderDetailBean feedOrderDetailBean = orderMapper.getFeedOrderDetailOneById(warehouse.getFeedOrder());
		map.put("materialCode", feedOrderDetailBean.getMaterialCode());
		map.put("loginCompany", warehouse.getCompany());
		//获取物料
		CompanyMaterialTableBean companyMaterial = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(map);
		if(feedOrderDetailBean.getType()==2) {
			Map<String,String> feedMap = new HashMap<String,String>();
			feedMap.put("materialType", feedOrderDetailBean.getMaterialType());
			feedMap.put("materialFactory", feedOrderDetailBean.getMaterialFactory());
			feedMap.put("loginCompany", myUser.getCompany()); 
			feedMap.put("lineNo", feedOrderDetailBean.getLineNo());
			feedMap.put("feedOrderId", feedOrderDetailBean.getFeedOrderId());
			feedMap.put("materialCode", feedOrderDetailBean.getMaterialCode());
			feedMap.put("type", "1");
			feedMap.put("status", "1");
			List<FeedOrderDetailBean> feedOrderDetailBeans = orderMapper.getFeedOrderDetailByDetail(feedMap);
			if(feedOrderDetailBeans==null|| feedOrderDetailBeans.size()<1) {
				throw new ServiceException("未查询到生产订单投料单");
			} 
			feedOrderDetailBean = feedOrderDetailBeans.get(0);
		}
		map.put("materialType", feedOrderDetailBean.getMaterialType());
		map.put("materialFactory", feedOrderDetailBean.getMaterialFactory());
		map.put("loginCompany", myUser.getCompany()); 
		map.put("lineNo", feedOrderDetailBean.getLineNo());
		map.put("feedOrderDetailId", feedOrderDetailBean.getFeedOrderId());
		//获取订单明细
		OrderInfoDetailBean orderInfoDetailBean = orderMapper.getOrderInfoDetailByDetailMap(map); 
		if(orderInfoDetailBean==null||orderInfoDetailBean.getFeedTotal().equals("")) {
			throw new ServiceException("订单无需此物料");
		}
		int count = 0;
		if(warehouse.getSelfOutFuCount()==0) {
			//订单投料数 
			BigDecimal feedTotal = new BigDecimal(orderInfoDetailBean.getFeedTotal());
			//投料单投料数
			BigDecimal feedCount = new BigDecimal(feedOrderDetailBean.getFeedCount().toString());
			BigDecimal productionFeedCount = new BigDecimal("0.0");
			if(feedOrderDetailBean.getProductionUnitFeedCount().doubleValue()>0) {
				productionFeedCount = new BigDecimal(feedOrderDetailBean.getProductionUnitFeedCount());
			}
			//订单数与投料数不同,进行数量换算
			BigDecimal warehouseCount =new BigDecimal("0.0");
			//出库数
			BigDecimal outCount = new BigDecimal(warehouse.getCount().toString());
			//如果单位一致,那么就是物料单位出库
			if(companyMaterial.getUnit().equals(warehouse.getInOutUnit())) {
				if(feedTotal.subtract(productionFeedCount).doubleValue()==0) {
					warehouseCount = outCount;
				}else if(feedTotal.subtract(productionFeedCount).doubleValue()<0) {
					warehouseCount =new BigDecimal(outCount.doubleValue()*((productionFeedCount.doubleValue()-feedTotal.doubleValue())/feedCount.doubleValue())+"");
				}else {
					warehouseCount =new BigDecimal(outCount.doubleValue()*((feedTotal.doubleValue()-productionFeedCount.doubleValue())/feedCount.doubleValue())+"");
				} 
			}else {  
				warehouseCount = outCount;
			} 
			count = (int)Math.floor(warehouseCount.doubleValue());
		}else {
			count = warehouse.getSelfOutFuCount();
		}
		ReportBean reportBean = new ReportBean();
		//如果颜色描述为空,则填写色号 
		if(orderInfoDetailBean.getColorDescription()==null||orderInfoDetailBean.getColorDescription().trim().equals("") ||orderInfoDetailBean.getColorDescription().equals("无")) {
			if(orderInfoDetailBean.getMaterialModel()==null ||orderInfoDetailBean.getMaterialModel().equals("无") || orderInfoDetailBean.getMaterialModel().equals("")) {
				throw new ServiceException("无颜色描述与规格不能报工");
			} 
			reportBean.setColor(orderInfoDetailBean.getMaterialModel());
		}else { 
			reportBean.setColor(orderInfoDetailBean.getColorDescription());
		} 
		//订单编号
		reportBean.setOrderId(orderInfoDetailBean.getOrderNo());
		//行号
		reportBean.setRowIndex(feedOrderDetailBean.getLineNo());
		//车间id
		reportBean.setWorkShopName(warehouse.getWorkShopId());
		//加工对象(物料类型)
		reportBean.setMachining(feedOrderDetailBean.getMaterialType());
		//状态
		reportBean.setStatus(1);
		//出库Id
		reportBean.setOtherId(warehouse.getId());
		//类型
		reportBean.setOtherType(-1);
		//合格数
		reportBean.setQualified(count);
		//不合格数
		reportBean.setNoQualified(0);
		//出入库出库数量
		reportBean.setMaterialCount(warehouse.getCount());
		//出入库单位
		reportBean.setMaterialUnit(warehouse.getInOutUnit());
		//物料代码
		reportBean.setMaterialCode(warehouse.getMaterialCode());
		reportBean.setReport("0");
		//审核人
		reportBean.setAuditor(myUser.getUserId());
		//审核时间
		reportBean.setAuditorTime(dateString);
		//工序
		ProcessBean processBean = basicDataService.getProcessByWorkShopId(reportBean.getWorkShopName());
		//获取车间对象 
		WorkshopProductionCycleBean workshopProductionCycleBean = basicDataMapper.getWorkshopById(reportBean.getWorkShopName());
	    Assert.notNull(workshopProductionCycleBean,"未获取到车间");
		//判断是否有设置交接入库工序
	    Assert.notNull(processBean,workshopProductionCycleBean.getWorkshopName()+"没有设置交接入库工序");
		//工序id
		reportBean.setProcedur(processBean.getId()); 
		reportBean.setProcedurText(processBean.getProcessName()); 
		//转为json对象
		JSONArray jsonObject = JSONArray.fromObject(reportBean);
		return jsonObject.toString();
	}
	
	/**
	 * 保存其他仓库(报废仓/待处理仓)的入库单
	* @date 2018年6月14日 上午8:38:07 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String saveInOtherWarehouse(Map map) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = simpleDateFormat.format(new Date());
		//获取前台传过来的入库数据
		String otherWarehouseArrJson = map.get("array").toString();
		//解析为json对象
		JSONArray jsonArray = JSONArray.fromObject(otherWarehouseArrJson);
		//解析为bean
		List<CompanyMaterialTableBean> companyMaterialTableBeans = (List<CompanyMaterialTableBean>) JSONArray.toCollection(jsonArray, CompanyMaterialTableBean.class);
		//用于保存的入库单
		List<OtherWarehouseBean> otherWarehouseBeans = new ArrayList<OtherWarehouseBean>();
		//用于处理订单采购的list
		List<PurchaseOrderDetailBean> purchaseOrderDetailBeans = new ArrayList<PurchaseOrderDetailBean>();
		//用于处理库存采购的list
		List<PurchaseDetailBean> purchaseDetailBeans = new ArrayList<PurchaseDetailBean>();
		//发消息的list
		List<String> message = new ArrayList<String>();
		CompanyMaterialTableBean companyMaterialTableBean = null;
		Map<String,Object> paramMap = new HashMap<String,Object>();
		//1为订单采购,2库存采购
		int type = 0;
		for(CompanyMaterialTableBean cmtb:companyMaterialTableBeans) {
			if(cmtb.getType()==1) {//订单采购单入库
				//获取投料单采购单对应表
				PurchaseOrderDetailBean purchaseOrderDetailBean = companyMaterialMapper.getPurchaseOrderDetailById(cmtb.getPurchaseDetailId());
				if(purchaseOrderDetailBean==null) {
					throw new ServiceException("无投料单采购单对应表异常");
				}
				PurchaseDetailBean purchaseDetailBean = companyMaterialMapper.getPurchaseDetailById(purchaseOrderDetailBean.getPurchaseDetailId());
				if(purchaseDetailBean==null) {
					throw new ServiceException("无采购单明细异常");
				}
				paramMap.put("materialCode", purchaseDetailBean.getMaterialCode());
				paramMap.put("loginCompany", map.get("loginCompany"));
				companyMaterialTableBean = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(paramMap);
				if(companyMaterialTableBean==null) {
					throw new ServiceException("无物料异常");
				}else {
		    		if("禁用".equals(companyMaterialTableBean.getStatus())) {
		    			throw new ServiceException("该物料已禁用,入库失败");
		    		}
				}
				paramMap.clear();
				Double count = cmtb.getCount()==null?0.0:cmtb.getCount();
				BigDecimal inCount = new BigDecimal(count.toString());
	    		BigDecimal purchaseCount = new BigDecimal(purchaseOrderDetailBean.getPurchaseCount().toString());
	    		BigDecimal purchaseInCount = new BigDecimal(purchaseOrderDetailBean.getInCount().toString());
			    if(inCount.subtract((purchaseCount.subtract(purchaseInCount))).doubleValue()>0) {
				    throw new ServiceException(purchaseDetailBean.getMaterialName()+"最多还可入库"+(purchaseCount.subtract(purchaseInCount).doubleValue()));
			    } 
			    //如果入库数等于采购数状态修改为已完成
			    if(inCount.subtract((purchaseCount.subtract(purchaseInCount))).doubleValue()==0) {
			    	purchaseOrderDetailBean.setIsFinish(1);
			    }
			    purchaseOrderDetailBean.setInCount(inCount.add(purchaseInCount).doubleValue());
			    //保存采购单
			    purchaseOrderDetailBeans.add(purchaseOrderDetailBean);
				OtherWarehouseBean otherWarehouseBean = new OtherWarehouseBean();
				otherWarehouseBean.setCompany(map.get("loginCompany").toString());
				otherWarehouseBean.setCreateTime(dateString);
				otherWarehouseBean.setCreateUser(map.get("loginUserId").toString());
				otherWarehouseBean.setInOutType(1);//1 入库 2出库
				otherWarehouseBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
				otherWarehouseBean.setMaterialType(purchaseOrderDetailBean.getMaterialType());
				otherWarehouseBean.setSumMoneyCount(cmtb.getSumMoneyCount());//入库结算数量
				otherWarehouseBean.setInCountPrice(cmtb.getInCountPrice());
				otherWarehouseBean.setInCountUnit(cmtb.getInCountUnit());
				otherWarehouseBean.setPosition(cmtb.getPositions());
				otherWarehouseBean.setMaterialName(purchaseDetailBean.getMaterialName());
				otherWarehouseBean.setColor(purchaseDetailBean.getColor());
				otherWarehouseBean.setModel(purchaseDetailBean.getModel());
				otherWarehouseBean.setProviderName(purchaseDetailBean.getProviderName());
				otherWarehouseBean.setColorDescription(cmtb.getColorDescription());
				if(cmtb.getDefaultWarehouse().equals("2")) {//2报废仓 3待处理仓
					//待处理仓中存放合格数
					otherWarehouseBean.setCount(inCount.doubleValue());
				}else if(cmtb.getDefaultWarehouse().equals("3")) {
					//报废仓存放不合格数 
					otherWarehouseBean.setCount(inCount.doubleValue());
				}
				otherWarehouseBean.setOrderId(purchaseOrderDetailBean.getOrderId());
				otherWarehouseBean.setRowIndex(Integer.parseInt(purchaseOrderDetailBean.getLineNo()));
				otherWarehouseBean.setSource(2);
				otherWarehouseBean.setStatus(0);
				otherWarehouseBean.setWarehouseType(Integer.parseInt(cmtb.getDefaultWarehouse()));
				otherWarehouseBean.setPurchaseDetailId(cmtb.getPurchaseDetailId());
				otherWarehouseBean.setInOutUnit(companyMaterialTableBean.getUnit());
				String rkId = DingTalkMapper.getApprovalNo("RK");
				otherWarehouseBean.setId(rkId);
				message.add(rkId);
				otherWarehouseBeans.add(otherWarehouseBean);
			}else if(cmtb.getType()==2) {//库存采购单入库
				//为库存采购
				type = 2;
				//获取采购单明细表
				PurchaseDetailBean purchaseDetailBean = companyMaterialMapper.getPurchaseDetailById(cmtb.getPurchaseDetailId());
				if(purchaseDetailBean==null) {
					throw new ServiceException("无采购单明细表异常");
				}
				paramMap.put("materialCode", purchaseDetailBean.getMaterialCode());
				paramMap.put("loginCompany", map.get("loginCompany"));
				companyMaterialTableBean = companyMaterialMapper.getCompanyMaterialTableByMaterialCode(paramMap);
				if(companyMaterialTableBean==null) {
					throw new ServiceException("无物料异常");
				}
				paramMap.clear();
				Double count = cmtb.getCount()==null?0.0:cmtb.getCount();
				BigDecimal inCount = new BigDecimal(count.toString());
	    		BigDecimal purchaseCount = new BigDecimal(purchaseDetailBean.getPurchaseCount().toString());
	    		BigDecimal purchaseInCount = new BigDecimal(purchaseDetailBean.getInCount().toString());
			    if(inCount.subtract((purchaseCount.subtract(purchaseInCount))).doubleValue()>0) {
				    throw new ServiceException(purchaseDetailBean.getMaterialName()+"最多还可入库"+(purchaseCount.subtract(purchaseInCount).doubleValue()));
			    } 
			    //如果入库数等于采购数状态修改为已完成
			    if(inCount.subtract((purchaseCount.subtract(purchaseInCount))).doubleValue()==0) {
			    	purchaseDetailBean.setIsFinish(1);
			    }
			    purchaseDetailBean.setInCount(inCount.add(purchaseInCount).doubleValue());
			    //保存采购单
			    purchaseDetailBeans.add(purchaseDetailBean);
				OtherWarehouseBean otherWarehouseBean = new OtherWarehouseBean();
				otherWarehouseBean.setCompany(map.get("loginCompany").toString());
				otherWarehouseBean.setCreateTime(dateString);
				otherWarehouseBean.setCreateUser(map.get("loginUserId").toString());
				otherWarehouseBean.setInOutType(1);//1 入库 2出库
				otherWarehouseBean.setMaterialCode(companyMaterialTableBean.getMaterialCode());
				otherWarehouseBean.setMaterialType(companyMaterialTableBean.getMaterialType());
				otherWarehouseBean.setSumMoneyCount(cmtb.getSumMoneyCount());//入库结算数量
				otherWarehouseBean.setInCountPrice(cmtb.getInCountPrice());
				otherWarehouseBean.setInCountUnit(cmtb.getInCountUnit());
				otherWarehouseBean.setPosition(cmtb.getPositions());
				otherWarehouseBean.setMaterialName(purchaseDetailBean.getMaterialName());
				otherWarehouseBean.setColor(purchaseDetailBean.getColor());
				otherWarehouseBean.setModel(purchaseDetailBean.getModel());
				otherWarehouseBean.setProviderName(purchaseDetailBean.getProviderName());
				otherWarehouseBean.setColorDescription(cmtb.getColorDescription());
				if(cmtb.getDefaultWarehouse().equals("2")) {//2报废仓 3待处理仓
					//待处理仓中存放合格数
					otherWarehouseBean.setCount(inCount.doubleValue());
				}else if(cmtb.getDefaultWarehouse().equals("3")) {
					//报废仓存放不合格数
					otherWarehouseBean.setCount(inCount.doubleValue());
				} 
				otherWarehouseBean.setOrderId("");
				otherWarehouseBean.setSource(3);
				otherWarehouseBean.setStatus(0);
				otherWarehouseBean.setWarehouseType(Integer.parseInt(cmtb.getDefaultWarehouse()));
				otherWarehouseBean.setPurchaseDetailId(cmtb.getPurchaseDetailId());
				otherWarehouseBean.setInOutUnit(companyMaterialTableBean.getUnit());
				String rkId = DingTalkMapper.getApprovalNo("RK");
				otherWarehouseBean.setId(rkId);
				message.add(rkId);
				otherWarehouseBeans.add(otherWarehouseBean);
			}
			if(otherWarehouseBeans.size()>0) {
				//插入入库记录  
				otherWarehouseMapper.insertOtherWarehouseByList(otherWarehouseBeans);
				otherWarehouseBeans.clear();
			}
		}
		
        //修改订单采购
	    if(purchaseOrderDetailBeans !=null && purchaseOrderDetailBeans.size()>0) {
	    	companyMaterialMapper.updatePurchaseOrderDetail(purchaseOrderDetailBeans);
	    }
	    if(purchaseDetailBeans !=null && purchaseDetailBeans.size()>0) {
	    	 map.put("listPurchaseDetail", purchaseDetailBeans);
	    	 companyMaterialMapper.updatePurchaseDetail(map);
	    }
	    //有未审核的,发微信消息通知
	    String mString = "";
	    if(message.size()>0) {
	    	String title = "";
	    	String bodyMessage = "";
	    	Map<String,Object> messageMap = new HashMap<String,Object>();
	    	messageMap.put("loginUserId",map.get("loginUserId"));
	    	messageMap.put("loginUserName",map.get("loginUserName"));
	    	messageMap.put("loginCompany",map.get("loginCompany"));
	    	if(type==1) {
	    		title = "订单采购入库";
	    		bodyMessage = title+" 需审核数据条数:"+message.size();
	    	}else {
	    		title = "库存采购入库";
	    		bodyMessage = title+" 需审核数据条数:"+message.size();
	    	}
	    	String queryCondition = "?ids="+message.toString().substring(1,message.toString().length()-1).replace(" ","");
	    	mString = this.sendWechatMessage(title, 2, bodyMessage, dateString, messageMap, RedirectUrlUtil.queryWarehouse+queryCondition, 1);
	    }
		return mString;
	}
	
	/**
	 * 获取报废仓待处理仓的出入库信息
	* @date 2018年6月29日 下午8:01:27 
	* @author 李斌
	* @return List<CompanyMaterialTableBean> 
	* @throws 
	 */
	public List<WarehouseInOutDetailBean> getOtherWarehouseMateiral(Map<String, Object> map){
		return	companyMaterialMapper.getOtherWarehouseMateiral(map);
	}
	
	/**
	 * 通过订单编号和行号获取订单信息
	* @date 2018年7月25日 下午3:18:32 
	* @author 李斌
	* @return List<OrderInfoDetailBean> 
	* @throws
	 */ 
	public List<OrderInfoDetailBean> getMaterialOkDetailByOrder(Map map) {
		List<OrderInfoDetailBean> orderInfoDetailList = orderMapper.getOrderInfoDetailByOrderIdAndLineNo(map);
		return orderInfoDetailList;
	}
	
	
	/**
	 * @throws ParseException 
	 * 采购入库自动结算
	* @date 2018年8月8日 下午1:47:10 
	* @author 李斌
	* @return void 
	* @throws
	 */
	public void autoSumMoneyByWarehouseIn(WarehouseInOutDetailBean warehouseInOutDetailBean,Map<String,Object> map) throws ParseException {
			Map<String,Object> custMap = new HashMap<String,Object>();
			String pri="";
			if(warehouseInOutDetailBean.getIsStages()==0) {//如果不是分期  按照之前是逻辑
//				//是出库
//				if(warehouseInOutDetailBean.getType()==9) {
//					custMap.put("customerName", warehouseInOutDetailBean.getCustomerName());
//					pri = warehouseInOutDetailBean.getCustomerName();
//				}else {
//					custMap.put("customerName", warehouseInOutDetailBean.getProviderName());
//					pri=warehouseInOutDetailBean.getProviderName();
//				}
//				custMap.put("loginCompany", warehouseInOutDetailBean.getCompany());
//				List<CustomerBean> customerBeans = basicDataMapper.getCustomerListByCustomerName(custMap);
//				if(customerBeans!=null && customerBeans.size()>0) {
//					//0代表现金结
//					if("0".equals(customerBeans.get(0).getPaymentWay())) {
//						Double inOutMoney = warehouseInOutDetailBean.getInOutMoney()==null?0:warehouseInOutDetailBean.getInOutMoney();
//						BigDecimal money = new BigDecimal("0.0");
//						//如果有传出入库金额，以传值为准，否则以算值为准
//						if(inOutMoney==0) {
//							//入库结算金额
//							BigDecimal inCountPrice = new BigDecimal("0.0");
//							//入库结算数量
//							BigDecimal sumMoneyCount = new BigDecimal("0.0");
//							//结算金额
//							if(warehouseInOutDetailBean.getType()==9) {
//								if(warehouseInOutDetailBean.getOutCountPrice()!=null) {
//									inCountPrice = new BigDecimal(warehouseInOutDetailBean.getOutCountPrice().toString());
//								}
//								if(warehouseInOutDetailBean.getCount()!=null) {
//									sumMoneyCount = new BigDecimal(warehouseInOutDetailBean.getCount().toString());
//								}
//							}else {
//								if(warehouseInOutDetailBean.getInCountPrice()!=null) {
//									inCountPrice = new BigDecimal(warehouseInOutDetailBean.getInCountPrice().toString());
//								}
//								if(warehouseInOutDetailBean.getSumMoneyCount()!=null) {
//									sumMoneyCount = new BigDecimal(warehouseInOutDetailBean.getSumMoneyCount().toString());
//								}
//							}
//							money = inCountPrice.multiply(sumMoneyCount);
//						}else {
//							money=new BigDecimal(inOutMoney.toString());
//						}
//						//更新结算
//						SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
//						String dateStr=simpleDateFormat.format(new Date());
//						custMap.put("id", warehouseInOutDetailBean.getId());
//						custMap.put("money", money.doubleValue());
//						custMap.put("balanceTime", dateStr);
//						custMap.put("balanceUser", map.get("loginUserId"));
//						custMap.put("isBalance", "1"); 
//						int row = warehouseInSumMoneyMapper.setIsBalanceByWarehouseInSumId(custMap);
//						Assert.isTrue(row>0,"入库结算失败");
//						//一下为附加收付款代码
//						map.put("money", money.doubleValue());
//						warehouseInSumMoneyService.notPayAutobalance(map,warehouseInOutDetailBean.getType(),"自动现金结算",pri,warehouseInOutDetailBean.getId());
////					int updateRow=warehouseInSumMoneyMapper.updateReceiptPaymentPrice(payMap);
////					Assert.isTrue(updateRow>0,ReturnStringUtil.UPDATE_ERROR); 
//					}
//				}
			}else {//如果是分期，按照分期的逻辑算好下一次付款时间，金额
				  //下一次付款时间  目前日期+分期间隔
				  SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM");
				  String toDay=TimeAndUnix.subMonth(simpleDateFormat.format(new Date())+"-28 00:00:00", warehouseInOutDetailBean.getStagesInterval());
				  //下一次付款金额  （总额-已付）/剩余期数
				  BigDecimal inOutMoney=new BigDecimal(warehouseInOutDetailBean.getInOutMoney());
				  BigDecimal receiptPaymentPrice=new BigDecimal(warehouseInOutDetailBean.getReceiptPaymentPrice());
				  BigDecimal stagesCount=new BigDecimal(warehouseInOutDetailBean.getStagesCount());
				  warehouseInOutDetailBean.setPayTime(toDay);
				  warehouseInOutDetailBean.setTotalPayable(inOutMoney.divide(stagesCount).doubleValue());
				  int  row=companyMaterialMapper.setStagesDetail(warehouseInOutDetailBean);
			}
	}

	/**
	 * 获取本月分期付款应付记录
	 * @return
	 */
	public List<WarehouseInSumMoneyBean> getAllThisMonthStages() {
		return companyMaterialMapper.getAllThisMonthStages();
	}

	/**
	 * 设置出入库分期信息
	 * @param warehouseInSumMoneyBeans
	 */
	public void setInOutStageDateil(List<WarehouseInSumMoneyBean> warehouseInSumMoneyBeans) {
		companyMaterialMapper.setInOutStageDateil(warehouseInSumMoneyBeans);
	}



}
